<?php
/**
 *    退款维权管理员控制器
 *
 *    @author    Garbin
 *    @usage    none
 */
class RefundApp extends BackendApp {

    var $_order_mod;
    var $_order_log_mod;
    var $_order_extm_mod;
    var $_goods_mod;
    var $_ordergoods_mod;
    var $_refund_mod;
    var $_store_mod;
    var $_member_mod;
    var $_refund_message_mod;

    function __construct() {
        $this->RefundApp();
    }

    function RefundApp() {
        parent::__construct();
        $this->_order_mod = &m('order');
        $this->_order_log_mod = &m('orderlog');
        $this->_order_extm_mod = &m('orderextm');
        $this->_goods_mod = &m('goods');
        $this->_ordergoods_mod = &m('ordergoods');
        $this->_refund_mod = &m('refund');
        $this->_store_mod = &m('store');
        $this->_member_mod = &m('member');
        $this->_refund_message_mod = &m('refund_message');
    }

    function index() {
        $sort_order = str_replace('_', ' ', trim($_GET['sort_order']));
        if (!empty($sort_order)) {
            $order = $sort_order . ',created desc';
        } else {
            $order = 'created desc';
        }

        $ask_customer = trim($_GET['ask_customer']);
        if ($ask_customer == 'yes' || $ask_customer == 'no') {
            $ask_customer = $ask_customer == 'yes' ? 1 : 0;
            $conditions = 'ask_customer=' . $ask_customer;
        } elseif ($ask_customer == 'all') {
            $conditions = '';
        } else {
            $conditions = '';
        }

        $page = $this->_get_page(10);   //获取分页信息
        $refunds = $this->_refund_mod->find(array(
            'conditions' => $conditions,
            'limit' => $page['limit'],
            'order' => $order,
            'count' => true
        ));
        $page['item_count'] = $this->_refund_mod->getCount();

        foreach ($refunds as $key => $refund) {
            $store = $this->_store_mod->get(array('conditions' => 'store_id=' . $refund['seller_id'], 'fields' => 'store_name,owner_name'));
            $refunds[$key]['store_name'] = $store['store_name'];
            $refunds[$key]['seller_name'] = $store['owner_name'];

            $member = $this->_member_mod->get(array('conditions' => 'user_id=' . $refund['buyer_id'], 'fields' => 'user_name'));
            $refunds[$key]['buyer_name'] = $member['user_name'];
            $goods = $this->_goods_mod->get(array('conditions' => 'goods_id=' . $refund['goods_id'], 'fields' => 'goods_name'));
            $refunds[$key]['goods_name'] = $goods['goods_name'];

            $order = $this->_order_mod->get(array('conditions' => 'order_id=' . $refund['order_id'], 'fields' => 'order_sn'));
            $refunds[$key]['order_sn'] = $order['order_sn'];
        }
        $this->_format_page($page);
        $this->assign('page_info', $page);

        $this->assign('refunds', $refunds);
        $this->display('refund.index.html');
    }

    function view() {
        $refund_id = empty($_GET['refund_id']) ? 0 : intval($_GET['refund_id']);
        if (!$refund_id) {
            $this->show_warning('refund_id_miss', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
            return;
        }

        //  读取退款信息
        $refund = $this->_refund_mod->get($refund_id);

        if (!$refund) {
            $this->show_warning('refund_not_find', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
            return;
        }

        if (!IS_POST) {
            $order = $this->_order_mod->get($refund['order_id']);
            $order['items'] = $this->_ordergoods_mod->find(array(
                'conditions' => 'order_id=' . $refund['order_id'],
            ));
            $order['shipping'] = $this->_order_extm_mod->get($refund['order_id']);

            $page = $this->_get_page(10);   //获取分页信息
            $refund['message'] = $this->_refund_message_mod->find(array(
                'conditions' => 'refund_id=' . $refund_id,
                'order' => 'created desc',
                'limit' => $page['limit'],
                'count' => true
            ));
            $page['item_count'] = $this->_refund_message_mod->getCount();
            $this->_format_page($page);
            $this->assign('page_info', $page);
            $this->assign('refund', $refund);
            $this->assign('order', $order);
            $this->display('refund.view.html');
        } else {
            $this->_check_post_data($refund);
            
             if($_POST['checkresult']=='no')
            {
                
                $this->admin_log(Lang::get('refund_fail'),1);
                $this->_refund_mod->edit($refund_id, array('status' => 'FAILED', 'end_time' => gmtime(), 'ask_customer' => 1));
                
                $content = sprintf(Lang::get('admin_agree_refund_content_change'), Lang::get('system_customer'),'0','0','平台客服留言:'.$_POST['content']);
                $data = array(
                    'owner_id' => $refund['seller_id'],
                    'owner_role' => 'seller',
                    'refund_id' => $refund_id,
                    'content' => $content,
                    'created' => gmtime()
                );
                $this->_refund_message_mod->add($data);

                $this->show_message('system_handle_refund_ok', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
                exit;
            }
            ini_set('display_errors','on');
            error_reporting(E_ALL);
            $order_id = $refund['order_id'];
            $order_info = $this->_order_mod->get($order_id);
            $out_trade_no = $order_info["order_sn"];
            $total_fee = $refund["total_fee"] * 100;
            $refund_fee = $refund["total_fee"] * 100;
            $refund_alifee = $refund["total_fee"];
            if($order_info['payment_code'] == 'epaywxnative' || $order_info['payment_code'] == 'wxpay_app'){
                include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Data.php";
                include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Api.php";
                include_once ROOT_PATH."/includes/payments/epaywxnative/lib/WxPay1.Config.php";
                $input = new WxPayRefund();
                $input->SetOut_trade_no($out_trade_no);
                $input->SetTotal_fee($total_fee);
                $input->SetRefund_fee($refund_fee);
                $config = new WxPay1Config();
                $input->SetOut_refund_no($refund['refund_sn']);
//            $input->SetOp_user_id($config->GetMerchantId());
                $rs = WxPay1Api::refund($config,$input, 60);
//                $this->printf_info(WxPay1Api::refund($config,$input, 60));
                if($rs['return_code'] != 'SUCCESS'){
                    $this->show_warning('退款失败', 'back_list', 'index.php?app=refund');
                    return;
                }
            }else if($order_info['payment_code'] == 'epayalipay' || $order_info['payment_code'] == 'alipay_app'){
                $config = include_once ROOT_PATH."/includes/payments/epayalipay/epayalipayrefund/config.php";
                include_once ROOT_PATH."/includes/payments/epayalipay/epayalipayrefund/pagepay/service/AlipayTradeService.php";
                include_once ROOT_PATH."/includes/payments/epayalipay/epayalipayrefund/pagepay/buildermodel/AlipayTradeRefundContentBuilder.php";
                //商户订单号，商户网站订单系统中唯一订单号
                $out_trade_no = trim($out_trade_no);

                //支付宝交易号
//                $trade_no = trim($_POST['WIDTRtrade_no']);
                //请二选一设置

                //需要退款的金额，该金额不能大于订单金额，必填
                $refund_amount = trim($refund_alifee);

                //退款的原因说明
//                $refund_reason = trim($_POST['WIDTRrefund_reason']);

                //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
//                $out_request_no = trim($_POST['WIDTRout_request_no']);

                //构造参数
                $RequestBuilder=new AlipayTradeRefundContentBuilder();
                $RequestBuilder->setOutTradeNo($out_trade_no);
//                $RequestBuilder->setTradeNo($trade_no);
                $RequestBuilder->setRefundAmount($refund_amount);
//                $RequestBuilder->setOutRequestNo($out_request_no);
//                $RequestBuilder->setRefundReason($refund_reason);
                $aop = new AlipayTradeService($config,true);

                $response = $aop->Refund($RequestBuilder);
                $rs = json_decode($response,true);
                if($rs['alipay_trade_refund_response']['code'] != '10000'){

                }else{
                    $this->_member_mod->db->query('rollback');
                    $this->show_warning('退款失败', 'back_list', 'index.php?app=refund');
                    return;
                }
            }
            if ($order_info['payment_code'] == 'cod' || $order_info['payment_code'] == 'bank' || $order_info['payment_code'] == 'post' || $order_info['payment_code'] == '') {
                $this->show_warning('payment_not_support_refund', 'back_list', 'index.php?app=refund');
                return;
            }
            //判断是否已完成,如果未完成先结束订单
            $this->auto_refund_confirm_order($order_info);
            //修改管理员设置价格 ， 重新获取 信息
            $refund_shipping_fee = $_POST['refund_shipping_fee'] ? $_POST['refund_shipping_fee'] : 0;
            $this->_member_mod->db->query('start transaction');
            $refund = $this->_refund_mod->get($refund_id);
            if(($refund['refund_goods_fee'] != floatval($_POST['refund_goods_fee'])) || ($refund['refund_shipping_fee'] != $refund_shipping_fee)){
                $refund['refund_goods_fee']=floatval($_POST['refund_goods_fee']);
                $refund['refund_shipping_fee']=$refund_shipping_fee;
                $mysql_flag=$this->_refund_mod->edit($refund_id, array('refund_goods_fee' => $refund['refund_goods_fee'], 'refund_shipping_fee' => $refund['refund_shipping_fee']));
                if(!$mysql_flag){
                    $this->_member_mod->db->query('rollback');
                    $this->show_warning('系统繁忙，请重试');return;
                }
            }

            


            //退款金额
            $money = $refund['refund_goods_fee'] + $refund['refund_shipping_fee'];
            $time = gmtime();
            //同意退款,卖家扣除金额。
            $seller_data = array(
                'user_id' => $order_info['seller_id'],
                'user_name' => '',
                'order_id' => $order_info['order_id'],
                'order_sn' => $order_info['order_sn'],
                'type' => ACCOUNT_TYPE_REFUND_OUT,
                'money_flow' => 'outlay',
                'money' => $money,
                'complete' => 1,
                'log_text' => '您同意给买家' . $order_info['buyer_name'] . '购买的产品退款' . $money . '元，订单号为:' . $order_info['order_sn'] . ',退款编号为:' . $refund_id,
                'add_time' => $time,
            );
            
            $mysql_flag =$this->_member_mod->change_money($seller_data);
            if(!$mysql_flag){
                $this->_member_mod->db->query('rollback');
                $this->show_warning('系统繁忙，请重试');return;
            }

            //同意退款,买家增加金额
//            $buyer_data = array(
//                'user_id' => $order_info['buyer_id'],
//                'user_name' => '',
//                'order_id' => $order_info['order_id'],
//                'order_sn' => $order_info['order_sn'],
//                'type' => ACCOUNT_TYPE_REFUND_IN,
//                'money_flow' => 'income',
//                'money' => $money,
//                'complete' => 1,
//                'log_text' => $order_info['seller_name'] . '同意给你购买的产品退款' . $money . '元，订单号为:' . $order_info['order_sn'] . ',退款编号为:' . $refund_id,
//                'add_time' => $time,
//            );
//            $mysql_flag =$this->_member_mod->change_money($buyer_data);
//            if(!$mysql_flag){
//                $this->_member_mod->db->query('rollback');
//                $this->show_warning('系统繁忙，请重试');return;
//            }
            
            // 对 退货进行处理 BEGUN
            $mysql_flag =$this->_refund_mod->edit($refund_id, array('status' => 'SUCCESS', 'end_time' => gmtime(), 'ask_customer' => 1));
            if(!$mysql_flag){
                $this->_member_mod->db->query('rollback');
                $this->show_warning('系统繁忙，请重试');return;
            }
            $content = sprintf(Lang::get('admin_agree_refund_content_change'), Lang::get('system_customer'), $refund['refund_goods_fee'], $refund['refund_shipping_fee'], $_POST['content']);
            $data = array(
                'owner_id' => $order_info['seller_id'],
                'owner_role' => 'seller',
                'refund_id' => $refund_id,
                'content' => $content,
                'created' => gmtime()
            );
            $this->_refund_message_mod->add($data);
   
            // 对 退货进行处理 END
            $this->_member_mod->db->query('commit');
            $this->admin_log(Lang::get('refund_suc'),1);
            
            $this->show_message('system_handle_refund_ok', 'back_list', 'index.php?app=refund&act=view&refund_id=' . $refund_id);
        }
    }

    //当卖家同意退款 订单自动确认收货
    function auto_refund_confirm_order($order_info) {

        $order_id = $order_info['order_id'];

        //判断订单是否已完成，未完成订单则自动完成
        if ($order_info['status'] != ORDER_FINISHED) {
            $this->_order_mod->db->query('start transaction');
//            lichen 2019/6/21 start
            $mysql_flag=$this->_order_mod->edit($order_info['order_id'], array('status' => 50, 'finished_time' => gmtime()));
//            $mysql_flag=$this->_order_mod->edit($order_info['order_id'], array('status' => ORDER_FINISHED, 'finished_time' => gmtime()));
//            lichen 2019/6/21 end
            if(!$mysql_flag){
                $this->_member_mod->db->query('rollback');
                $this->show_warning('系统繁忙，请重试');exit;
            }
            /* 记录订单操作日志 */
            $order_log = & m('orderlog');
            $order_log->add(array(
                'order_id' => $order_id,
                'operator' => 0,
                'order_status' => order_status($order_info['status']),
                'changed_status' => order_status(ORDER_FINISHED),
                'remark' => Lang::get('admin_agree_refund_order_status_change'),
                'log_time' => gmtime(),
                'operator_type' => 'seller',
            ));
            

            /* 更新定单状态 开始***************************************************** */
            $this->account_mod_log = & m('account_log');
            $account_log_row = $this->account_mod_log->getrow("select * from " . DB_PREFIX . "account_log where order_id='$order_id' and type=" . ACCOUNT_TYPE_BUY);
            $sell_user_id = $order_info['seller_id']; //卖家ID
            $buyer_user_id = $account_log_row['user_id']; //买家ID
            if ($account_log_row['order_id'] == $order_id) {

                $temp_order = $this->_order_mod->get($order_id);
                $money = $temp_order['order_amount']; //定单价格
                
                $sell_money_row = $this->_member_mod->getAll('SELECT * FROM '.$this->_member_mod->table.' WHERE user_id='.$sell_user_id.' FOR UPDATE');
                if(is_array($sell_money_row) && !empty($sell_money_row)){
                    $sell_money_row= current($sell_money_row);
                $sell_money = $sell_money_row['money']; //卖家的资金
                $sell_money_dj = $sell_money_row['money_dj']; //卖家的冻结资金
                $new_money = $sell_money + $money;
                $new_money_dj = $sell_money_dj - $money;
                //更新数据
                $new_money_array = array(
                    'money' => $new_money,
                    'money_dj' => $new_money_dj,
                );
                $new_buyer_account_log = array(
                    'money' => $money,
                    'complete' => 1,
                    'states' => 40,
                );
                $new_seller_account_log = array(
                    'money' => $money,
                    'complete' => 1,
                    'states' => 40,
                );
                $mysql_flag=$this->_member_mod->edit('user_id=' . $sell_user_id, $new_money_array);
                if(!$mysql_flag){
                    $this->_member_mod->db->query('rollback');
                    $this->show_warning('系统繁忙，请重试');exit;
                }
                $mysql_flag=$this->account_mod_log->edit("order_id={$order_id} AND user_id={$sell_user_id} AND type=".ACCOUNT_TYPE_SELLER." AND money_flow='income' AND complete=0", $new_seller_account_log);
                if(!$mysql_flag){
                    $this->_member_mod->db->query('rollback');
                    $this->show_warning('系统繁忙，请重试');exit;
                }
                $mysql_flag=$this->account_mod_log->edit("order_id={$order_id} AND user_id={$buyer_user_id} AND type=".ACCOUNT_TYPE_BUY." AND money_flow='outlay' AND complete=0", $new_buyer_account_log);
                if(!$mysql_flag){
                    $this->_member_mod->db->query('rollback');
                    $this->show_warning('系统繁忙，请重试');exit;
                }
                }else{
                    $this->_member_mod->db->query('rollback');
                    $this->show_warning('卖家不存在');exit;
                }

            }
            /* 更新定单状态 结束***************************************************** */
            $this->_order_mod->db->query('commit');
        }
    }

    function _check_post_data($refund = array()) {

        if ($refund['status'] == 'SUCCESS' || $refund['status'] == 'CLOSED' || $refund['status'] == 'FAILED') {
            $this->show_warning('add_refund_message_not_allow');
            exit;
        }
        if (empty($_POST['refund_goods_fee']) || floatval($_POST['refund_goods_fee']) < 0) {
            $this->show_warning('refund_fee_ge0');
            exit;
        } elseif (floatval($_POST['refund_goods_fee']) > $refund['goods_fee']) {
            $this->show_warning('refund_fee_error');
            exit;
        }
        if ($_POST['refund_shipping_fee'] != '' && floatval($_POST['refund_shipping_fee']) < 0) {
            $this->show_warning('refund_shipping_fee_ge0');
            exit;
        }
        if (floatval($_POST['refund_shipping_fee']) > $refund['shipping_fee']) {
            $this->show_warning('refund_shipping_fee_error');
            exit;
        }
    }

    function printf_info($data)
    {
        foreach($data as $key=>$value){
            echo "<font color='#f00;'>$key</font> : ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
        }
    }

}

?>
